<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-form-item label="农舍名称" prop="houseName">
        <el-input v-model="formData.houseName" placeholder="请输入农舍名称" />
      </el-form-item>
      <el-form-item label="农舍类型" prop="type">
        <el-select v-model="formData.type" placeholder="请选择农舍类型">
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.FARM_FARMHOUSE_TYPE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="笼位数量"  prop="sum">
        <el-input-number v-model="formData.sum"  placeholder="请输入笼位数量" style="width:250px" />
      </el-form-item>
      <el-form-item label="农场" prop="farmId">
        <el-tree-select
          v-model="formData.farmId"
          :data="farmList"
          :props="defaultProps"
          check-strictly
          node-key="id"
          placeholder="请选择归属农场"
          @change="handleFarmChange"
        />
      </el-form-item>
      <el-form-item label="部门" prop="deptId">
        <el-tree-select
          v-model="formData.deptId"
          :data="deptList"
          :props="defaultProps"
          check-strictly
          node-key="id"
          placeholder="请选择归属部门"
          @change="hangdleChange"
        />
      </el-form-item>
      <el-form-item label="饲养员" prop="userId">
        <el-select v-model="formData.userId" multiple placeholder="请选择饲养员">
          <el-option
            v-for="keeper in keepers"
            :key="keeper.id"
            :label="keeper.nickname"
            :value="keeper.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="农舍状态" prop="status">
        <el-select v-model="formData.status" placeholder="请选择农舍状态">
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.COMMON_STATUS)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="备注">
        <el-input v-model="formData.description" placeholder="请输入内容" type="textarea" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import {ref,reactive} from 'vue'
import{getIntDictOptions , DICT_TYPE } from '@/utils/dict'
import { HouseApi, houseVO } from '@/api/farm/house'
import { FarmTourApi,FarmTourVO } from '@/api/farmTour/index';//农场列表
import { defaultProps, handleTree } from '@/utils/tree'
import * as DeptApi from '@/api/system/dept'
import { log } from 'console'
import { any, number } from 'vue-types'
import { it } from 'node:test'
import { fromPairs } from 'lodash-es'
/** 农舍管理 表单 */
defineOptions({ name: 'HouseForm' })
const deptList = ref<Tree[]>([]) // 树形结构
const farmList = ref<Tree[]>([])//农场树形结构
const keepers = ref([]);//饲养员


const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改

const formData = ref({
  id: undefined,
  houseName: undefined,
  type: undefined,
  description: undefined,
  deptId: undefined,
  userId: [],
  status: 0,
  sum:undefined
})
const formRules = reactive({
  houseName: [{ required: true, message: '农舍名称不能为空', trigger: 'blur' }],
  type: [{ required: true, message: '农舍名称不能为空', trigger: 'blur' }],
  deptId: [{ required: true, message: '部门不能为空', trigger: 'blur' }],
  status: [{ required: true, message: '农舍状态不能为空', trigger: 'change' }],
  sum: [{ required: true, message: '农舍数量不能为空', trigger: 'blur' },
    {type:'number', message: '只能输入数字' }
  ],
})
const formRef = ref() // 表单 Ref

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()

  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await HouseApi.getHouse(id);
      console.log(formData.value,'formData.value');
      // 将类型转换为数字类型
      formData.value.type *= 1;
      // 根据部门ID获取饲养员列表
      fetchKeepers(formData.value.deptId);
    } finally {
      formLoading.value = false
    }
  }
  // 加载农场
  FarmTourApi.getFarmTour().then(res=>{
    // 处理农场数据并获取相应ID
    const processedFarmData = handleTree(res);//加载部门树
    const farmIds = processedFarmData.map(farmId=>({id:farmId.id,name:farmId.name}))//获取部门id和name
    console.log(farmIds,'farmIds');
    
    farmList.value = processedFarmData;
  })

}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗
  // 加载部门
  DeptApi.getSimpleDeptList().then(res =>{
    // 处理部门数据并获取相应ID
    const processedData = handleTree(res);//加载部门树
    const deptIds = processedData.map(dept=>({id:dept.id,name:dept.name}))//获取部门id和name
    deptList.value = processedData;
  })

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    // 显式地将 sum 转换为数字类型
    formData.value.sum = Number(formData.value.sum)
    const data = formData.value as unknown as HouseApi.houseVO
    if (formType.value === 'create') {
      await HouseApi.createHouse(data)
      message.success(t('common.createSuccess'))
    } else {
      await HouseApi.updateHouse(data)
      message.success(t('common.updateSuccess'))
      // 重置表单
      resetForm()
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value= {
    id: undefined,
    houseName: undefined,
    type: undefined,
    description: undefined,
    deptId: undefined,
    userId: [],
    status: 0,
    sum:undefined
  }
  formRef.value?.resetFields()
  // 清空饲养员信息
  keepers.value = []
}

// 选择农场获取部门列表
const handleFarmChange =async(selectedNodes)=>{
  try{
    const res = await HouseApi.deptApi({ farmId: selectedNodes });
    console.log(res,'res农场');
    const processedDeptData = handleTree(res); // 处理返回的部门数据
    deptList.value = processedDeptData; // 更新部门列表
    formData.value.deptId = undefined;//清空部门
    keepers.value = []; // 清空饲养员列表
    console.log(deptList.value, '部门ID数组');
  }catch(error){
    console.error('部门列表失败', error);
  }
}

// 选择部门获取部门depeID
const hangdleChange=(selectedNodes)=>{
  if(selectedNodes){
    const selectedDeptId =selectedNodes;
    console.log(selectedDeptId,'selectedDeptId');
    // 根据部门ID获取饲养员列表
    fetchKeepers(selectedDeptId);
  }
}
// 根据部门ID获取饲养员列表
const fetchKeepers=(selectedDeptId)=>{
  HouseApi.sectionHouseApi(selectedDeptId).then(res=>{
    console.log(res,'饲养员');
    keepers.value =res
    console.log(typeof(keepers.value,'keepers'));
  })
}

</script>